
<template>
  <el-dialog   :close-on-click-modal="false" ref="dlg" :visible="true"
   @close="onclosedlg">
    <el-card class="form">
      <form-schema ref="formSchema" :schema="schema" v-model="model" @change="onchange">
        <el-button type="primary" @click="submit" v-if="mode !== 'view' ">提交</el-button>
        <el-button type="reset" @click="cancel">取消</el-button>
      </form-schema>
    </el-card>
    <el-dialog :append-to-body="true" :visible.sync="errorVisible">
      <el-alert
        :closable="false"
        :title="error"
        type="error"
      >
      </el-alert>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import FormSchema from '@/components/FormSchema'
  import { Option } from 'element-ui'
  import { getUser } from '@/utils/auth'
  import SelectDate  from '@/components/SelectDate'
  import linq from 'linq'
  // import eventBus from '@/utils/eventBus'
  FormSchema.setComponent('form', 'el-form', ({ vm }) => {
    // vm is the FormSchema VM
    const labelWidth = '120px'
    const model = vm.data
    const rules = {}
    vm.fields.forEach((field) => {
      const type = field.schemaType === 'array' && field.type === 'radio'
        ? 'string'
        : field.schemaType
      const required = field.required
      const message = field.title
      const trigger = ['radio', 'checkbox', 'select'].includes(field.type)
        ? 'change' : 'blur'

      // http://element.eleme.io/#/en-US/component/form#validation
      rules[field.name] = { type, required, message, trigger }
    })
    // returning the form props
    return { labelWidth, rules, model }
  })
  // http://element.eleme.io/#/en-US/component/form#validation

  FormSchema.setComponent('label', 'el-form-item', ({ field }) => ({
    prop: field.name
  }))
  FormSchema.setComponent('email', 'el-input')
  FormSchema.setComponent('text', 'el-input')
  FormSchema.setComponent('textarea', 'el-input')
  FormSchema.setComponent('checkbox', 'el-checkbox')
  FormSchema.setComponent('switch', 'el-switch')
  FormSchema.setComponent('radio', 'el-radio')
  FormSchema.setComponent('select', 'el-select')
  FormSchema.setComponent('date', SelectDate)
  FormSchema.setComponent('number', 'el-input-number')
  // You can also use the component object
  FormSchema.setComponent('option', Option)

  // By default `<h1/>` is used to render the form title.
  // To override this, use the `title` type:
  FormSchema.setComponent('title', 'h2')

  // By default `<p/>` is used to render the form title.
  // To override this, use the `description` type:
  FormSchema.setComponent('description', 'small')
  // By default `<div/>` is used to render the message error.
  // To override this, use the `error` type:
  FormSchema.setComponent('error', 'el-alert', ({ vm }) => ({
    type: 'error',
    title: vm.error
  }))
  export default {
    props: ['jsonForm', 'data', 'mode','project','cate','custom'],
    data: () => {
      return ({
        errorVisible:false,
        schema: {},
        error:'',
        model: null,
      })
    },
    watch: {
      // This would be called anytime the value of title changes
      data(newValue, oldValue) {
        this.model = newValue;
        // you can do anything here with the new value or old/previous value
      },
    },
    created() {
      console.log("mode:"+this.mode)
      let custom = this.custom?this.custom:[];
      this.model = this.data;
      this.schema = require('@/schema/' + this.jsonForm)
      
      custom.forEach(e=>{
        let pro =  this.schema.properties[e.pro];
        pro[e.key] = e.val;
        this.schema.required.push(e.pro);
      })
     
    },
    methods: {
      onchange(val){
        this.$emit('change',this.model, val)
      },
      cancel() {
        this.$refs.formSchema.reset();
        this.$emit('cancel', false)
      },
      onclosedlg(){
        this.$emit('cancel', false)
        this.$refs.formSchema.reset();
      },
      submit(e) {

        //console.log(this.model)
        console.log("submit")
        this.$refs.formSchema.form().validate( async (valid) => {
          if (valid) {

            try {

              this.model.project = this.project;
              this.model.cate = this.cate;
              // var check = new Promise((resolve, reject) => eventBus.$emit('check', this.model, resolve, reject));
              // await check;
              if (this.mode === 'add') {
                this.$emit('add', this.model)
              }
              if (this.mode === 'update') {
                console.log("we update")
                this.$emit('update', this.model)
              }
            }catch(err)
            {
              this.error = JSON.stringify(err);
              this.errorVisible = true;
            }
          }
        })

        // this.model contains the valid data according your JSON Schema.
        // You can submit your model to the server here
      }
    },
    components: { FormSchema }
  }
</script>

<style>

</style>
